<template>
  <!-- # 巡检记录 -->
  <div style="margin-top: 15px;">
    <!-- ## 搜索栏 -->
    <el-row style="background-color: #FFFFFF;">
      <el-form ref="searchForm" label-width="100px" :rules="searchRules" :modle="searchData" style="display:flex;margin-top:8px ">
        <el-form-item label="服务器名称">
          <el-input v-model="searchData.serverName" />
        </el-form-item>
        <el-form-item label="巡检人">
          <el-input v-model="searchData.inspector" />
        </el-form-item>
        <el-form-item label="服务器状态">
          <el-select v-model="searchData.status" placeholder="服务器状态">
            <el-option label="正常" value="0" />
            <el-option label="异常" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label-width="50px">
          <el-button type="primary" plain @click="handleSearch">搜索</el-button>
        </el-form-item>
        <el-form-item label-width="60px">
          <el-button type="primary" icon="el-icon-refresh" circle @click="handleRefresh" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain @click="addDuty">添加巡检</el-button>
        </el-form-item>
        <el-form-item style="padding-right: 20px;">
          <el-button type="primary" @click="exportExcelSelect">导出数据</el-button>
        </el-form-item>
      </el-form>
    </el-row>

    <!-- ## 表格 -->
    <el-table v-loading="loading" element-loading-text="正在加载中" :data="tableData" style="width: 99%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" />
      <el-table-column width="80" type="index" label="序号" />

      <el-table-column label="姓名" width="180" align="center">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <p>ID: {{ scope.row.id }}</p>
            <p>姓名: {{ scope.row.inspector }}</p>
            <p>管理主机: {{ scope.row.serverName }}</p>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">{{ scope.row.inspector }}</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column label="巡检日期" width="250">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span style="margin-left: 10px">{{ formatDate(scope.row.inspectionDate) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="服务器IP" width="120" prop="serverName" />

      <el-table-column label="状态" width="180" align="center">
        <template slot-scope="scope">
          <el-tag size="medium" :type="scope.row.status == '0' ? 'success' : 'danger'">
            {{ scope.row.status === '0' ? '正常' : '异常' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="备注信息" width="240" prop="remarks" />

      <el-table-column label="更新时间" width="250">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span style="margin-left: 10px">{{ formatDate(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" width="250">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span style="margin-left: 10px">{{ formatDate(scope.row.createTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" min-width="150" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="info" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
      <template v-slot:empty>
        <div style="height: 200px;">
          <img src="../../assets/nodata.png" width="150" style="margin: 30px;">
        </div>
      </template>
    </el-table>
    <!-- ## 分页 -->
    <el-pagination
      :page-size="size"
      :current-page.sync="page"
      layout="sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- ## 弹层 -->
    <el-dialog :title="isEdit ? '编辑' : '添加'" :visible.sync="dialogVisible" width="50%">
      <div>
        <el-form ref="formDateRef" :rules="rules" label-position="right" label-width="80px" :model="formDate">
          <el-form-item label="巡检人" prop="inspector">
            <el-input v-model="formDate.inspector" />
          </el-form-item>
          <el-form-item label="服务器IP" prop="serverName">
            <el-input v-model="formDate.serverName" />
          </el-form-item>
          <el-form-item label="巡检日期" prop="inspectionDate">
            <el-col :span="11">
              <el-date-picker v-model="formDate.inspectionDate" type="datetime" placeholder="选择日期时间" />
            </el-col></el-form-item>

          <el-form-item label="主机状态" prop="status">
            <el-radio-group v-model="formDate.status">
              <el-radio :label="0">正常</el-radio>
              <el-radio :label="1">异常</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="备注信息">
            <el-input v-model="formDate.remarks" />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelBtn">取 消</el-button>
        <el-button type="primary" @click="verBtn">确 定</el-button>
      </span>
    </el-dialog>
    <!-- ## 表格导出预览 -->
    <el-dialog title="表格保存预览" width="70%" :visible.sync="selectWindow">
      <el-table id="tableData" :data="selectData" height="380px">
        <el-table-column width="80" type="index" label="序号" align="center" />
        <el-table-column label="巡检日期" width="250" align="center">
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.inspectionDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="inspector" label="姓名" align="center" />

        <el-table-column prop="serverName" label="主机名" align="center" />
        <el-table-column label="状态" width="180" align="center" >
          <template slot-scope="scope">
            <el-tag size="medium" :type="scope.row.status === 0 ? 'success' : 'danger'">
              {{ scope.row.status === 0 ? '正常' : '异常' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注信息" align="center" />
        <el-table-column label="更新时间" width="250" align="center">
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.updateTime) }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="exportExcel">确定导出</el-button>
      </div>
    </el-dialog>

  </div>

</template>

<script>
import { getPatrol, delPatrol, addPatrol, changePatrol } from '@/api/patrol.js'
import htmlToExcel from '@/utils/htmlToExcel.js'
import { formatDate } from '@/utils/index.js'

export default {
  name: 'OperationDuty',
  data() {
    return {
      tableData: [], // 表格数据
      selectData: [],
      // 添加 编辑数据
      formDate: {
        inspector: '', // 巡检人
        serverName: '', // 主机名
        inspectionDate: '', // 巡检日期
        status: '', // 主机状态（0正常；1异常）
        remarks: '' // 备注信息
      },
      searchData: {
        serverName: '', // 服务器名称
        inspector: '', // 巡检人
        status: '' // 服务器状态
      },
      rules: {
        inspector: [{ required: true, message: '请输入巡检人', trigger: 'blur' }],
        serverName: [{ required: true, validator: this.validateIP, trigger: 'blur' }],
        inspectionDate: [{ required: true, message: '请选择巡检日期', trigger: 'blur' }],
        status: [{ required: true, message: '选择主机状态', trigger: 'blur' }]
      },
      dialogVisible: false, // 弹层是否开启
      isEdit: true, // 是否是编辑
      selectWindow: false,
      loading: true,
      total: 0,
      size: 10,
      page: 1
    }
  },
  mounted() {
    this.getPatrol()
  },
  methods: {
    formatDate,
    commonHandle(res) {
      this.tableData = res.records
      this.total = res.total
      this.size = res.size
      this.loading = false
    },
    // 获取表格数据
    async getPatrol() {
      if (this.searchData.serverName === '' && this.searchData.inspector === '' && this.searchData.status === '') {
        const res = await getPatrol(this.page, this.size)
        this.commonHandle(res)
      } else {
        const res = await getPatrol(this.page, this.size, this.searchData)
        this.commonHandle(res)
      }
    },
    // 新增
    addDuty() {
      this.formDate = {
        inspectionDate: '',
        inspector: '',
        remarks: '',
        serverName: '',
        status: ''
      }
      this.dialogVisible = true
      this.isEdit = false
    },
    // 编辑
    handleEdit(row) {
      console.log('id:', row.id)
      this.dialogVisible = true
      this.isEdit = true
      this.formDate = {
        id: row.id,
        inspectionDate: row.inspectionDate,
        inspector: row.inspector,
        remarks: row.remarks,
        serverName: row.serverName,
        status: Number(row.status)
      }
    },
    // 删除
    handleDelete(row) {
      console.log('id:', row.id)
      this.$confirm('此操作将删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delPatrol(row.id)
        await this.getDutyData()
      }).catch(() => {
      })
    },
    // 弹层 取消
    cancelBtn() {
      this.dialogVisible = false
    },
    // 弹层 确认
    async verBtn() {
      // 编辑-确认
      if (this.isEdit) {
        this.$refs.formDateRef.validate(async isok => {
          if (isok) {
            // 编辑接口
            console.log(this.formDate)
            await changePatrol(this.formDate)
            await this.getPatrol()
            this.$message({
              message: '编辑成功！',
              type: 'success'
            })
            this.dialogVisible = false
          }
        })
        this.dialogVisible = false
        // 添加-确认
      } else {
        console.log(this.formDate)
        this.$refs.formDateRef.validate(async isok => {
          if (isok) {
            await addPatrol(this.formDate)
            await this.getPatrol()
            this.$message({
              message: '添加成功！',
              type: 'success'
            })
            this.dialogVisible = false
          }
          this.dialogVisible = false
        })
        this.dialogVisible = false
        await this.getPatrol()
        this.$nextTick(() => {
          this.loading = false // 假设这是控制加载状态的变量
        })
        // 添加接口
      }
    },
    // 分页-每页条数
    handleSizeChange(size) {
      this.loading = true
      this.size = size
      this.page = 1
      this.getPatrol()
    },
    // 分页-页码
    handleCurrentChange(page) {
      this.loading = true
      this.page = page
      this.getPatrol()
    },
    // 导出
    exportExcel() {
      htmlToExcel.getExcel('#tableData', '巡检记录')
    },
    exportExcelSelect() {
      if (this.selectData.length < 1) {
        this.$message.error('请选择要导出的内容！')
        return false
      }
      this.selectWindow = true
    },
    handleSelectionChange(val) {
      this.selectData = val
    },
    validateIP(rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入服务器IP地址'))
      } else {
        const ipPattern = /^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])$/
        if (!ipPattern.test(value)) {
          callback(new Error('请输入有效的IP地址'))
        } else {
          callback()
        }
      }
    },
    async handleSearch() {
      this.loading = true
      await this.getPatrol()
    },
    async handleRefresh() {
      this.loading = true
      this.searchData.serverName = ''
      this.searchData.inspector = ''
      this.searchData.status = ''
      await this.getPatrol()
      this.loading = false
      this.size = 10
      this.page = 1
    }
  }
}
</script>

<style lang="scss" scoped></style>
